﻿using Css_VoteSys.Models.Database;
using Css_VoteSys.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Css_VoteSys.Controllers
{
    /// <summary>
    /// 投票分类（工程类、产品类、技术类）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CategoryController : ControllerBase
    {

        private readonly Css_VoteSysContext _db;
        private readonly IUserService _UserService;

        public CategoryController(Css_VoteSysContext db, IUserService UserService)
        {
            _db = db;
            _UserService = UserService;
        }

        /// <summary>
        /// 创建投票分类(需登录、管理员)
        /// </summary>
        /// <param name="CategoryName">投票分类名称</param>
        /// 
        /// <returns></returns>
        [HttpPost]
        public string CreateCategory(string CategoryName)
        {
            var UserId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
            if (UserId == null) { return "请先登录"; }
            var result = _UserService.IsRoot(Convert.ToInt32(UserId));
            if (result)
            {
                if (_db.Categories.Any(x => x.CategoryName == CategoryName)) return "奖项分类已存在";
                _db.Categories.Add(new Category
                {
                    CategoryName = CategoryName,
                });
                //保存更改
                var row = _db.SaveChanges();
                if (row > 0)
                    return "创建投票分类成功";
                return "创建投票分类失败";
            }
            return "您没有权限";
            
        }

        /// <summary>
        /// 查询所有投票分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<Category> SelectCategory() { 
            return _db.Categories.ToList();
        }
    }
}
